package com.lap.auth.adapter.driving.persistence.dict.repository;

import com.lap.auth.adapter.driving.persistence.dict.DictTypeConverter;
import com.lap.auth.adapter.driving.persistence.dict.mapper.DictTypeMapper;
import com.lap.auth.adapter.driving.persistence.dict.po.DictTypePo;
import com.lap.auth.domain.dict.DictType;
import com.lap.auth.domain.dict.repository.DictTypeRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class DictTypeRepositoryImpl implements DictTypeRepository {

  private final DictTypeConverter converter;
  private final DictTypeMapper dictTypeMapper;

  @Override
  public Integer save(DictType dictType) {
    DictTypePo dictTypePo = converter.toPo(dictType);
    if (dictType.isNew()) {
      dictTypeMapper.insert(dictTypePo);
      return dictTypePo.getId();
    }
    return dictTypeMapper.updateById(dictTypePo);
  }

  @Override
  public Integer deleteById(Integer id) {
    return dictTypeMapper.deleteById(id);
  }

  @Override
  public Optional<DictType> findById(Integer id) {
    DictTypePo dictTypePo = dictTypeMapper.selectById(id);
    DictType dictType = converter.toDomain(dictTypePo);
    return Optional.ofNullable(dictType);
  }

  @Override
  public Optional<DictType> findByCode(String code) {
    DictTypePo dictTypePo = dictTypeMapper.selectByCode(code);
    DictType dictType = converter.toDomain(dictTypePo);
    return Optional.ofNullable(dictType);
  }
}
